///
/// @ProjectName:    learning_rust
/// @Description:    
/// @File:           jz4.rs
/// @Author:         wujehy
/// @Email:          wujehy@qq.com
/// @Time:           2021-06-30 21:57
///
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Box<TreeNode>>,
    pub right: Option<Box<TreeNode>>,
}

impl TreeNode {
    #[inline]
    fn new(val: i32) -> Self {
        TreeNode {
            val: val,
            left: None,
            right: None,
        }
    }
}


struct Solution {}

impl Solution {
    fn new() -> Self {
        Solution {}
    }

    // /**
    //  * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
    //  *
    //  * @param pre int整型一维数组
    //  * @param vin int整型一维数组
    //  * @return TreeNode类
    //  */
    #[allow(non_snake_case)]
    pub fn reConstructBinaryTree(&self, pre: Vec<i32>, vin: Vec<i32>) -> Option<Box<TreeNode>> {
        // println!("current info pre= {} , vin = {} ", pre.len(), vin.len());
        // println!("prt = {:?}", &pre[..]);
        // println!("vin = {:?}", &vin[..]);
        // 没有数据了 返回 空
        if pre.is_empty() || vin.is_empty() {
            return None;
        }
        // 只有一个的时候就是 root

        let current_root_node = Option::Some(Box::new(TreeNode::new(pre[0])));
        println!("current : {}", pre[0]);
        // 否则就找到root
        // 寻找 分界点
        let mut vin_root_index = 0;
        for item in vin.as_slice() {
            if pre.get(0).unwrap().eq(&item) {
                println!("index {}", vin_root_index);
                break;
            } else {
                vin_root_index += 1;
            }
        };

        let current_root_node = current_root_node.map(|mut item: Box<TreeNode>| {
            if vin_root_index > 2 {
                item.left = self.reConstructBinaryTree((&pre[1..vin_root_index + 1]).to_vec(), (&vin[..vin_root_index]).to_vec());
            } else {
                item.left = Option::Some(Box::new(TreeNode::new(pre[1])));
            }
            if pre.len() - vin_root_index > 2 {
                item.right = self.reConstructBinaryTree((&pre[vin_root_index + 1..]).to_vec(), (&vin[vin_root_index + 1..]).to_vec());
            } else {
                item.right = Option::Some(Box::new(TreeNode::new(pre[vin_root_index + 1])));
            }
            return item;
        });

        current_root_node
    }
}

#[test]
fn test4() {
    let s = Solution::new();
    // let test1: Option<Box<ListNode>> = Option<Box<ListNode>>; {1,2,3};
    // let expext = vec! {1, 2, 5, 3, 4, 6, 7};
    let pre = vec![1, 2, 3, 4, 5, 6, 7];
    let vin = vec![3, 2, 4, 1, 6, 5, 7];

    let data = (&pre[0..2]).to_owned();
    println!("Data : {:?}", data);
    // assert_eq!(expext, s.reConstructBinaryTree(pre , vin));
    let data = s.reConstructBinaryTree(pre, vin);
    println!("data : {:?}", data);
}
